<script setup lang="ts">
import { type Ref, inject, onMounted, ref } from 'vue'
import { nextKey } from '../util'
import type { MenuItem } from './types'
import { injectKeyOfActiveKey } from './util'

const props = withDefaults(
  defineProps<{
    items: MenuItem[]
    activeEffect: boolean
  }>(),
  {
    items: () => [],
    activeEffect: false
  }
)

const activeKey = inject<Ref<string>>(injectKeyOfActiveKey, ref(''))

onMounted(() => {
  for (const e of props.items) {
    if (!e.key) {
      e.key = nextKey()
    }
  }
})

function onClick(item: MenuItem) {
  if (!item.children || item.onClick) {
    activeKey.value = item.key
  }
  if (item.onClick) {
    item.onClick()
  }
}
</script>
<template>
  <ul class="menu-list">
    <li v-for="(item, idx) in items" :key="idx">
      <a :class="{ 'is-active': item.key === activeKey }" @click="onClick(item)">
        <i v-if="item.icon" :class="item.icon" />
        {{ item.name }}
      </a>
      <MenuList v-if="item.children" :items="item.children" :active-key="activeKey" />
    </li>
  </ul>
</template>
